import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

public class ReaderLock implements AbstractLock {

	Semaphore writterIn = new Semaphore(1);

	AtomicInteger readersIn = new AtomicInteger(0);

	@Override
	public void readerIn() {
		try {
			writterIn.acquire();
			readersIn.incrementAndGet();
			writterIn.release();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Override
	public synchronized void readerout() {
		readersIn.decrementAndGet();
		notifyAll();
	}

	@Override
	public synchronized void witerIn() {
		while (readersIn.intValue() != 0)
			try {
				wait();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}

		try {
			writterIn.acquire();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	@Override
	public void writerout() {
		writterIn.release();
	}

}
